// blob下载
export const downloadBlob = (data, fileName) => {
  const blob = new Blob([data], {
    type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  });
  const url = window.URL.createObjectURL(blob);
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', fileName); // 设置下载文件名
  document.body.appendChild(link);
  link.click(); // 触发下载
};

// 文件下载
export const downloadByUrl = (url, downloadName) => {
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', `${downloadName}.docx`); // 设置下载文件名
  link.setAttribute('target', '_blank');
  document.body.appendChild(link);
  link.click(); // 触发下载
};

// 根据格式设置时间
// 预编译正则表达式
const formatRegex = /yyyy|MM|dd|HH|mm|ss/g;
const padRegex = /(d|H|m|s)(\d)/;
function pad(num) {
  return num < 10 ? '0' + num : num;
}

export function optimizedFormat(time, format) {
  const date = new Date(time);
  const year = date.getFullYear();
  let result = format.replace(formatRegex, (match) => {
    switch (match) {
      case 'yyyy':
        return year;
      case 'MM':
        return pad(date.getMonth() + 1);
      case 'dd':
        return pad(date.getDate());
      case 'HH':
        return pad(date.getHours());
      case 'mm':
        return pad(date.getMinutes());
      case 'ss':
        return pad(date.getSeconds());
    }
  });
  return result.replace(padRegex, (_, type, num) => {
    return num.length < 2 ? type + num : num;
  });
}
